from typing import *


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
        L = R = 0
        l = r = 0
        dist = 0

        def f(root, h):
            if root is None:
                return -1, False, -1, False
            if root.val == start:
                nonlocal dist
                dist = h
            a, b, c, d = f(root.left, h + 1)
            A, B, C, D = f(root.right, h + 1)

            return (
                max(a, c) + 1,
                b or d or root.val == start,
                max(A, C) + 1,
                B or D or root.val == start,
            )

        a, b, c, d = f(root, 0)
        if root.val == start:
            return max(a, c)
        if b:
            return max(a - dist, dist + c)
        return max(c - dist, a + dist)
